<?php

namespace app\common\model;

use helper\Storage as StorageSystem;
use helper\util\File;
use think\facade\Config;
use think\Image;
use think\model;

class Storage extends Model
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';

    /**
     * 获取器 - 文件状态
     * @param $value
     * @return mixed
     */
    public function getStatusAttr($value)
    {
        $status = [0=>'禁用',1=>'启用'];
        return $status[$value];
    }

    /**
     * 获取器 - 格式化文件大小
     * @param $value
     * @return string
     */
    public function getFileSizeAttr($value)
    {
        return File::formatBytes($value);
    }

    /**
     * 图片上传
     * @param $image
     * @param $user_id
     * @return array
     */
    public static function base64Image($image, $user_id)
    {
        if (!preg_match('/^(data:\s*image\/(\w+);base64,)/', $image, $result)) {
            return ['code' => 1, 'msg' => '图片Base64编码不正确'];
        }
        $ext        = $result[2] == 'jpeg' ? 'jpg' : $result[2];
        $image_name = md5((string)microtime(true)) . '.' . $ext;
        $path       = 'storage/';
        $img_url    = "image/" . date("Ymd") . "/";
        if (!is_dir("./" . $path . $img_url)) {
            mkdir("./" . $path . $img_url);
        }
        $image_file = $img_url . $image_name;
        if (!file_put_contents("./" . $path . $image_file, base64_decode(str_replace($result[1], '', $image)))) {
            return ['code' => 1, 'msg' => '图片保存失败'];
        }
        $data['user_id']   = $user_id;
        $data['file_name'] = $image_name;
        $data['file_md5']  = md5($image_name);
        $data['file_sha1'] = sha1($image_name);
        $data['file_ext']  = $ext;
        $data['file_size'] = 0;
        $data['file_path'] = $image_file;

        self::create($data);
        $file = self::putFile($image_file);
        if ($file['code']) {
            return ['code' => 1, 'msg' => '上传失败'];
        }
        return $file;
    }

    /**
     * 文件上传
     * @param string $file
     * @return array
     */
    public static function putFile($file)
    {
        $config = Config::get('filesystem');
        $data   = [];
        if (!in_array($config['default'], ['local', 'public'])) {
            $file_path = $config['disks']['public']['root'];
            $result    = StorageSystem::factory('oss', $config['disks'][$config['default']])->putFile($file, $file_path);
            if ($result['code']) {
                return ['code' => 1, 'msg' => $result['msg']];
            }
            $data['file_path'] = $config['disks'][$config['default']]['url'] . $file;
        }
        return ['code' => 0, 'data' => $data];
    }

    /**
     * 文件删除
     * @param string $file
     * @return array
     */
    public static function deleteFile($file)
    {
        $config = Config::get('filesystem');
        if (!in_array($config['default'], ['local', 'public'])) {
            $result  = StorageSystem::factory('oss', $config['disks'][$config['default']])->deleteFile($file);
            if ($result['code']) {
                return ['code' => 1, 'msg' => $result['msg']];
            }
        }
        return ['code' => 0, 'data' => $file];
    }

    /**
     * 生成缩略图
     * @param string $file 图片路径
     * @param int $width 最大宽度
     * @param int $height 最大高度
     * @return string
     */
    public static function createThumb(string $file, int $width = 200, int $height = 200)
    {
        $path_parts = pathinfo($file);
        $path_name  = $path_parts['dirname'] . '/' . $path_parts['filename'] . "_{$width}_$height.{$path_parts['extension']}";
        $image      = Image::open($file);
        $image->thumb($width, $height, 3)->save($path_name);
        return $path_name;
    }

    /**
     * 图片添加水印
     * @param $file
     * @param null $is_water
     */
    public static function setWater($file, $is_water = null)
    {
        if ($is_water == '0') {
            return true;
        }
        $path_parts = pathinfo($file);
        // 上传配置
        $config = [];
        $image  = Image::open($file);
        //图片水印
        if ($config['is_water'] == 1 || $is_water == '1') {
            $water_path = $path_parts['dirname'] . "/" . ltrim($config['water_img'], '/');
            if (!file_exists($water_path)) {
                return false;
            }
            $image->water($water_path, $config['water_locate'], $config['water_alpha']);
            $image->save($file->getPathName());
        }
        return true;
    }

    public static function sts()
    {
        $config = Config::get('filesystem');
        return StorageSystem::factory('cos', $config['disks'][$config['default']])->sts();
    }
}